<template>
  <div class="update-photo">
    <img :src="image" alt="" ref="image" class="image">
    <van-nav-bar
      class="toolbar"
      left-text="取消"
      right-text="完成"
      @click-left='$emit("close")'
      @click-right='onConfirm'
    >
    </van-nav-bar>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    file: {
      // type: String,
      required: true
    }
  },
  data () {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper: null // 裁切器实例
    }
  },
  computed: {},
  watch: {},
  mounted () {
    // 获取需要裁切的图片DOM
    const image = this.$refs.image
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
  },
  methods: {
    async onConfirm () {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true,
        duration: 0 // 为0持续展示,
      })
      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', file)

      await updateUserPhoto(fd)
      this.$emit('close')

      this.$emit('update-photo', window.URL.createObjectURL(file))
      this.$toast.success('保存成功')
    },
    getCroppedCanvas () { // 获取画布里面的信息
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    }
  }
}

</script>
<style lang='less' scoped>
.toolbar {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: #000;
}
image {
  display: block;
    /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>
